
import axios from 'axios'
import { getRedirectPath } from '../util'
import { AUTH_SUCCESS, LOGOUT, ERROR_MSG, LOAD_DATA } from './actiontypes'

const initState={
	redirectTo:'',
	msg:'',
	user:'',
	type:''
}

export function user(state=initState, action) {
	switch(action.type){
		case AUTH_SUCCESS:
			return {
				...state, msg:'',
				redirectTo: getRedirectPath(action.payload),
				...action.payload
			}		
		case LOAD_DATA:
			return {
				...state,
				...action.payload
			}
		case ERROR_MSG:
			return {
				...state,
				isAuth: false,
				msg: action.msg
			}
		case LOGOUT:
			return {
				...initState,
				redirectTo: '/login'
			}
		default:
			return state
	}
} 
// 用户登录成功
const authSuccess = (obj) => {
	const {pwd, ...data} = obj
	return { type: AUTH_SUCCESS, payload: data }
}
// 错误信息
const errorMsg = (msg) => {
	return { msg, type: ERROR_MSG }
}
// 登录信息
export const loadData = (userinfo) => {
	return { type: LOAD_DATA, payload: userinfo }
}
// 退出按钮
export const logoutSubmit = () => {
	return { type: LOGOUT }
}

export const update = (data) => {
	return dispatch => {
		axios.post('/user/update', data)
			.then(res=>{
				if (res.status===200&&res.data.code===0) {
					dispatch(authSuccess(res.data.data))
				} else {
					dispatch(errorMsg(res.data.msg))
				}
			})
	}
}

export const login = ({user, pwd}) => {
	if (!user||!pwd) {
		return errorMsg('请输入账号密码')
	}
	return dispatch => {
		axios.post('/user/login', {user, pwd})
			.then(res => {
				if (res.status===200&&res.data.code===0) {
					dispatch(authSuccess(res.data.data))
				} else {
					dispatch(errorMsg(res.data.msg))
				}
			})		
	}
}

export const registry = ({user, pwd, repeatpwd, type}) => {
	if (!user||!pwd||!type) {
		return errorMsg('请输入账号密码')
	}
	if (pwd !== repeatpwd) {
		return errorMsg('请确认密码')
	}
	return dispatch => {
		axios.post('/user/register', {user, pwd, type})
			.then(res => {
				if (res.status===200&&res.data.code===0) {
					dispatch(authSuccess({user, pwd, type}))
				} else {
					dispatch(errorMsg(res.data.msg))
				}
			})		
	}
}





